﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperScrollView;
using UnityEngine;
using UnityEngine.UI;

public class ShaProList : MonoBehaviour
{
    private InputField _inputField;

    private InputField _proInputField;

    public List<List<int>> reloadShuangseQiu()
    {
        List<List<int>> datas = new List<List<int>>();
        int max = 33;
        for (int i = 1; i <= max - 5; i++)
        {
            for (int i2 = i + 1; i2 <= max - 4; i2++)
            {
                for (int i3 = i2 + 1; i3 <= max - 3; i3++)
                {
                    for (int i4 = i3 + 1; i4 <= max - 2; i4++)
                    {
                        for (int i5 = i4 + 1; i5 <= max - 1; i5++)
                        {
                            for (int i6 = i5 + 1; i6 <= max; i6++)
                            {
                                datas.Add(new List<int> {i, i2, i3, i4, i5, i6});
                                //                                stream.WriteLine($"{i} , {i2} , {i3} , {i4} , {i5} , {i6}");
                            }
                        }
                    }
                }
            }
        }

        return datas;
    }

    public int disTimes = 50;
    public DuplexSha mDuplexSha = new DuplexSha();
    public SingeSha mSingeSha = new SingeSha();

    private void Start()
    {
        mDuplexSha.OnSuccessAction = list => { ShowTips("杀号完成"); };
        algorithmMax.Init();
        envCurData = reloadShuangseQiu();
        UIController.instance.Get("timesInputField").GetComponent<InputField>().onValueChanged.AddListener((value) =>
        {
            int.TryParse(value, out disTimes);
        });

        UIController.instance.Get("ShaBtn").GetComponent<Button>().onClick.AddListener(() =>
        {
            if (_inputField.text.Equals(""))
            {
                ShowTips("输入大复试，以英文,分割 例如 1,2,3,4,5");
                return;
            }

            var content = _inputField.text;
            //            content = content.Replace(" ", "");
            //            content = content.Replace('，', ',');
            //            content = content.Replace('.', ',');
            //            var sp_content = content.Split(',');
            _queue.Enqueue(content);

            var str = _queue.Dequeue();
            List<int> input_nums = GetNums(str);

            //            UIController.instance.Get("ShaBtn").GetComponent<Button>().enabled = false;
            object value = new List<List<int>>() {input_nums};
            DoubleInputArgs args = new DoubleInputArgs();
            args.args = value;
            args.shahaoType = ShaHaoType.Duplex;
            mDuplexSha.StartShaHao(args, envCurData);
//            algorithmMax.ShaMax(new List<List<int>>() {input_nums});
            //            StartShaBall(input_nums);
            //        Debug.Log("杀号" + content);

            //            _inputField.text     
        });

        UIController.instance.Get("DanShaBtn").GetComponent<Button>().onClick.AddListener(() =>
        {
            if (_inputField.text.Equals(""))
            {
                ShowTips("输入大复试，以英文,分割 例如 1,2,3,4,5");
                return;
            }

            var content = _inputField.text;
            //            content = content.Replace(" ", "");
            //            content = content.Replace('，', ',');
            //            content = content.Replace('.', ',');
            //            var sp_content = content.Split(',');
            _queue.Enqueue(content);

            var str = _queue.Dequeue();
            List<int> input_nums = GetNums(str);

            //            UIController.instance.Get("ShaBtn").GetComponent<Button>().enabled = false;
            object value = input_nums;
            DoubleInputArgs args = new DoubleInputArgs();
            args.args = value;
            args.shahaoType = ShaHaoType.SingNum;
            mSingeSha.StartShaHao(args, envCurData);
//            algorithmMax.ShaMax(new List<List<int>>() {input_nums});
            //            StartShaBall(input_nums);
            //        Debug.Log("杀号" + content);

            //            _inputField.text     
        });

        UIController.instance.Get("ResetBtn").GetComponent<Button>().onClick.AddListener(() =>
        {
            envCurData = reloadShuangseQiu();
            Deleted();
        });
        UIController.instance.Get("mutifyBtn").GetComponent<Button>().onClick.AddListener(() =>
        {
            string[] shaFile = UIController.instance.Get("Cal").GetComponent<CalComps>().loadHistoryData();
            List<List<int>> input_nums_array = new List<List<int>>();
            for (int i = 0; i < shaFile.Length; i++)
            {
                var ctx = shaFile[i];
                ctx = ctx.Replace(" ", "");
                ctx = ctx.Replace('，', ',');
                ctx = ctx.Replace('.', ',');
                ctx = ctx.Replace("、", ",");
//                _queue.Enqueue(ctx);

                List<int> input_nums = GetNums(ctx);
                input_nums_array.Add(input_nums);
            }

            //            UIController.instance.Get("ShaBtn").GetComponent<Button>().enabled = false;
            object value = input_nums_array;
            DoubleInputArgs args = new DoubleInputArgs();
            args.args = value;
            args.shahaoType = ShaHaoType.Duplex;
            mDuplexSha.StartShaHao(args, envCurData);
        });
        //        loadHistoryData
        UIController.instance.Get("loadBtn").GetComponent<Button>().onClick.AddListener(() =>
        {
            envCurData = UIController.instance.Get("Cal").GetComponent<CalComps>().loadFileData();
            Deleted();
        });
        UIController.instance.Get("saveBtn").GetComponent<Button>().onClick.AddListener(() =>
        {
            int cou = 0;
            ShowTips("开始保存 ");
            UIController.instance.Get("Cal").GetComponent<CalComps>()
                .SaveData(envCurData, (date) =>
                {
                    cou += 1;
                    ShowTips($"一共{envCurData.Count} 保存  {cou} 个");
                }, () => { ShowTips("............ "); });
        });

        _inputField = UIController.instance.Get("InputField").GetComponent<InputField>();
        _inputField.text = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16";
        mLoopListView = GetComponent<LoopListView2>();
        InitLoopView();
    }

    Queue<string> _queue = new Queue<string>();
    public List<List<int>> cacheData = new List<List<int>>();

    public List<int> GetNums(string content)
    {
        content = content.Replace(" ", "");
        content = content.Replace('，', ',');
        content = content.Replace('.', ',');
        content = content.Replace('、', ',');
        var sp_content = content.Split(',');

        List<int> input_nums = new List<int>();
        for (int i = 0; i < sp_content.Length; i++)
        {
            var ngnum = sp_content[i].Trim();
            int ret = -1;
            if (!int.TryParse(ngnum, out ret))
            {
                ShowTips("输入不合法 ,请检查一下");
                //                return ;
            }

            input_nums.Add(ret);
        }

        return input_nums;
    }

    private bool shaStatus = false;

    public Dictionary<int, int> flagDic = new Dictionary<int, int>()
    {
        [1] = 2,
        [2] = 1,
        [3] = 1,
        [4] = 0,
        [5] = 1,
        [6] = 0,
        [7] = 1,
        [8] = 0,
        [9] = 0,
        [10] = 0,
        [11] = 1,
        [12] = 0,
        [13] = 1,
        [14] = 0,
        [15] = 0,
        [16] = 0,
        [17] = 1,
        [18] = 0,
        [19] = 1,
        [20] = 0,
        [21] = 0,
        [22] = 0,
        [23] = 1,
        [24] = 0,
        [25] = 0,
        [26] = 0,
        [27] = 0,
        [28] = 0,
        [29] = 1,
        [30] = 0,
        [31] = 1,
        [32] = 0,
        [33] = 0,
    };

    public void StartShaBall(List<int> input_nums, int cNum = 0, ShaType type = ShaType.None)
    {
        List<List<int>> datas = new List<List<int>>();
        if (shaStatus == true)
        {
            return;
        }

        shaStatus = true;

        ShowTips("杀号中...");

        switch (type)
        {
            case ShaType.Cha:
                if (cNum == 0)
                {
                    shaStatus = false;
                    return;
                }

                ShowTips($"杀差值 {cNum}...");
                for (int i = 0; i < envCurData.Count; i++)
                {
                    var var_data = envCurData[i];
                    if (var_data[1] - var_data[0] == cNum && var_data[2] - var_data[1] == cNum &&
                        var_data[3] - var_data[2] == cNum && var_data[4] - var_data[3] == cNum &&
                        var_data[5] - var_data[4] == cNum)
                    {
                        datas.Add(var_data);
                    }
                }

                break;
            case ShaType.HeShu:
                for (int i = 0; i < envCurData.Count; i++)
                {
                    var var_data = envCurData[i];
                    int times = 0;
                    for (int j = 0; j < var_data.Count; j++)
                    {
                        if (flagDic[var_data[j]] == 0)
                        {
                            times += 1;
                        }
                    }

                    if (times == cNum)
                    {
                        datas.Add(var_data);
                    }
                }

                //                flagDic
                break;
            case ShaType.HeZhi:
                for (int i = 0; i < envCurData.Count; i++)
                {
                    var var_data = envCurData[i];
                    int times = 0;
                    for (int j = 0; j < var_data.Count; j++)
                    {
                        times += var_data[j];
                    }

                    if (times <= cNum)
                    {
                        datas.Add(var_data);
                    }
                }

                break;
            case ShaType.OuShu:
                for (int i = 0; i < envCurData.Count; i++)
                {
                    var var_data = envCurData[i];
                    int times = 0;
                    for (int j = 0; j < var_data.Count; j++)
                    {
                        if (var_data[j] % 2 == 0)
                        {
                            times += 1;
                        }
                    }

                    if (times == cNum)
                    {
                        datas.Add(var_data);
                    }
                }

                break;
            case ShaType.JiShu:
                for (int i = 0; i < envCurData.Count; i++)
                {
                    var var_data = envCurData[i];
                    int times = 0;
                    for (int j = 0; j < var_data.Count; j++)
                    {
                        if (var_data[j] % 2 == 1)
                        {
                            times += 1;
                        }
                    }

                    if (times == cNum)
                    {
                        datas.Add(var_data);
                    }
                }

                break;
            case ShaType.ZhiShu:
                //质数
                for (int i = 0; i < envCurData.Count; i++)
                {
                    var var_data = envCurData[i];
                    int times = 0;
                    for (int j = 0; j < var_data.Count; j++)
                    {
                        if (!flagDic.ContainsKey(var_data[j]))
                        {
                            Debug.LogError(var_data[j]);
                        }
                        else
                        {
                            if (flagDic[var_data[j]] == 1)
                            {
                                times += 1;
                            }
                        }
                    }

                    if (times == cNum)
                    {
                        datas.Add(var_data);
                    }
                }

                break;
            default:
                int count = input_nums.Count;

                int max = count;

                if (count == 6)
                {
                    datas.Add(input_nums);
                }
                else if (count < 6)
                {
                    datas.Add(input_nums);
                }
                else
                {
                    for (int i = 1; i <= max - 5; i++)
                    {
                        for (int i2 = i + 1; i2 <= max - 4; i2++)
                        {
                            for (int i3 = i2 + 1; i3 <= max - 3; i3++)
                            {
                                for (int i4 = i3 + 1; i4 <= max - 2; i4++)
                                {
                                    for (int i5 = i4 + 1; i5 <= max - 1; i5++)
                                    {
                                        for (int i6 = i5 + 1; i6 <= max; i6++)
                                        {
                                            datas.Add(new List<int>()
                                            {
                                                input_nums[i - 1], input_nums[i2 - 1], input_nums[i3 - 1],
                                                input_nums[i4 - 1],
                                                input_nums[i5 - 1],
                                                input_nums[i6 - 1]
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                break;
        }


        cacheData = datas;
        ShowTips($"要杀 {datas.Count} 单注");
    }

    public void InitLoopView()
    {
        mLoopListView.InitListView(envCurData.Count, OnGetItemByIndex);
    }

    LoopListViewItem2 OnGetItemByIndex(LoopListView2 listView, int index)
    {
        if (index < 0 || index >= envCurData.Count)
        {
            return null;
        }

        LoopListViewItem2 item = listView.NewListViewItem("item");
        LoopTwoBall itemScript = item.GetComponent<LoopTwoBall>();
        itemScript.SetData(envCurData[index].ToArray());
        itemScript.OnInit();
        return item;
    }

    #region data

    public List<List<int>> envCurData;

    #endregion

    private LoopListView2 mLoopListView;

    public string curTips = String.Empty;

    public void ShowTips(string str)
    {
        curTips = str;
    }

    private void Update()
    {
        if (curTips != String.Empty && curTips != "")
        {
            UIController.instance.Get("tipsText").GetComponent<Text>().text = curTips;
            curTips = String.Empty;
        }

        if (mDuplexSha.isRunStatus == ShaStatues.EndSha)
        {
            //            Debug.Log(algorithmMax._threadDatas);
            mDuplexSha.isRunStatus = ShaStatues.Idle;
            ShowTips($"杀号完成.... {(DateTime.Now - mDuplexSha.start_time).ToString()}");
            envCurData.Clear();
            for (int i = 0; i < mDuplexSha._threadDatas.Count; i++)
            {
                var data = mDuplexSha._threadDatas[i];
                envCurData.AddRange(data.curdata);
            }

            Deleted();
        }

        if (mSingeSha.isRunStatus == ShaStatues.EndSha)
        {
            //            Debug.Log(algorithmMax._threadDatas);
            mSingeSha.isRunStatus = ShaStatues.Idle;
            ShowTips($"杀号完成.... {(DateTime.Now - mSingeSha.start_time).ToString()}");
            envCurData.Clear();
            for (int i = 0; i < mSingeSha._threadDatas.Count; i++)
            {
                var data = mSingeSha._threadDatas[i];
                envCurData.AddRange(data.curdata);
            }

            Deleted();
        }
//        mSingeSha


        if (cacheData.Count > 0)
        {
            int times = disTimes;
            times = Math.Max(times, 100);
            times = Math.Min(times, 50);
            for (int i = 0; i < times; i++)
            {
                ///取到第一个要去除的数据
                var firstData = cacheData[0];
                cacheData.RemoveAt(0);

                var isSuccess = envCurData.FindIndex((elel) =>
                {
                    if (firstData.Count < 6)
                    {
                        bool firstSearch = true;

                        for (int j = 0; j < firstData.Count; j++)
                        {
                            if (!elel.Contains(firstData[j]))
                            {
                                firstSearch = false;
                                break;
                            }
                        }

                        return firstSearch;
                    }

                    if (firstData.Contains(0))
                    {
                        bool firstSearch = true;

                        for (int j = 0; j < firstData.Count; j++)
                        {
                            if (firstData[j] != 0 && elel[j] != firstData[j])
                            {
                                firstSearch = false;
                                break;
                            }
                        }

                        return firstSearch;
                    }

                    return elel[0] == firstData[0] && elel[1] == firstData[1] && elel[2] == firstData[2] &&
                           elel[3] == firstData[3] && elel[4] == firstData[4] && elel[5] == firstData[5];
                });
                List<int> removeData = new List<int>();
                if (isSuccess >= 0)
                {
                    removeData.AddRange(envCurData[isSuccess]);
                    envCurData.RemoveAt(isSuccess);
                    var isSuccess_2 = envCurData.FindIndex((elel) =>
                    {
                        if (firstData.Count < 6)
                        {
                            bool firstSearch = true;

                            for (int j = 0; j < firstData.Count; j++)
                            {
                                if (!elel.Contains(firstData[j]))
                                {
                                    firstSearch = false;
                                    break;
                                }
                            }

                            return firstSearch;
                        }

                        if (firstData.Contains(0))
                        {
                            bool firstSearch = true;

                            for (int j = 0; j < firstData.Count; j++)
                            {
                                if (firstData[j] != 0 && elel[j] != firstData[j])
                                {
                                    firstSearch = false;
                                    break;
                                }
                            }

                            return firstSearch;
                        }

                        return elel[0] == firstData[0] && elel[1] == firstData[1] && elel[2] == firstData[2] &&
                               elel[3] == firstData[3] && elel[4] == firstData[4] && elel[5] == firstData[5];
                    });
                    if (isSuccess_2 >= 0)
                    {
                        cacheData.Add(firstData);
                    }
                }

                //                Debug.Log(");
                StringBuilder builder = new StringBuilder();
                //                string strret = "";
                for (int j = 0; j < firstData.Count; j++)
                {
                    builder.Append($"{firstData[j].ToString()},");
                }

                string appendStr = "";
                for (int j = 0; j < removeData.Count; j++)
                {
                    builder.Append($"     {removeData[j].ToString()},");
                }

                //                removeData
                //                Debug.Log($"{strret}");
                ShowTips(
                    $" 杀 组合 中 {builder}........");

                if (cacheData.Count == 0)
                {
                    Deleted();
                    UIController.instance.Get("ShaBtn").GetComponent<Button>().enabled = true;
                    if (_queue.Count == 0)
                    {
                        shaStatus = false;
                        //                        Debug.Log($" {str}");
                        return;
                    }

                    shaStatus = false;
                    var str = _queue.Dequeue();
                    Debug.Log($"杀号 {str}");
                    List<int> input_nums = GetNums(str);

                    UIController.instance.Get("ShaBtn").GetComponent<Button>().enabled = false;
                    StartShaBall(input_nums);

                    return;
                }
            }
        }
    }

    public void ShaCha(int cha)
    {
    }


    private void OnDestroy()
    {
        mDuplexSha.Release();
    }

    public void Deleted()
    {
        mLoopListView.SetListItemCount(envCurData.Count, false);
        mLoopListView.RefreshAllShownItem();
        ShowTips("剩余 ： " + envCurData.Count.ToString());
    }
}